<?php

namespace App\Http\Controllers;


use App\Datas\GoogleShell;
use App\Datas\AppleShell;
use App\Datas\EventList;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Tools\Oss;
use App\Tools\Task;
use App\Tools\MuseFrame;
use App\Tools\Curl;


class   ShellController extends Controller
{


    /**
     * 校验google支付订单
     */

    public function checkGooglePayOrder(){
        set_time_limit(0);
        $result = GoogleShell::checkGoogleOrder();
    }


    public function delRedisKey(Request $request){

        $key = $request->get('key');

        $res = Redis::del($key);

        echo $res;die;
    }


    public function checkApplePayOrder(){

        set_time_limit(0);
        $result = AppleShell::checkAppleOrder();

    }

    /**
     * 作图中心回调通知
     */
    public function imgWebHooks(Request $request){

        $data = $request->post();
        if (empty($data)) {
            $data = file_get_contents("php://input");
            $data = json_decode($data, true);
        }

        Log::info('imgWebHooks'.$data['task_id'], [$data]);

        $res = (new Task())->webHooks($data);

        return json_encode(['code'=>$res['code'], 'msg'=>$res['msg']]);

    }

    /**
     * 删除过期的作图任务
     */
    public function autoDelTaskImg(){
        $time = date('Y-m-d H:i:s');
        $list = DB::table('task_img')->where('status',1)->where('expire_time','<=', $time)->select('id')->get()->toArray();
        $ids = array_column($list, 'id');
        DB::table('task_img')->whereIn('id',$ids)->delete();
        echo '删除-'.count($ids).'-条';

    }



    public function tongji(Request $request){

        $time = trim($request->get('time'));
        if (empty($time)) {
            return '请输入日期，格式为 YYYY-MM-DD';
        }
        $end = $time.' 23:59:59';
        $device_ids = DB::table('user')->where('created_at','>=',$time)->where('created_at','<=',$end)->pluck('device_id')->toArray();
        if (!empty($device_ids)) {
            $arr = [];
            foreach ($device_ids as $key => $value) {
                $arr[]= "'".$value."'"; 
            }
            $str = implode(',', $arr);
            $ch_sql = "select count(distinct(device_id)) as total_amount from event_list where descriptors_type = '1' and  name ='Board_LowButton_clicked' and device_id in (".$str.")";

            $data = EventList::getInstance()->select($ch_sql)->rows();

            return $data[0]['total_amount']; 
        }

    }

    public function bathDelOpusImg(Request $request){
        $user_id = $request->get('user_id',0);
        $limit = $request->get('limit',0);
        if (!$user_id) {
            return "用户ID不能为空";
        }
        if (!$limit) {
            return "删除条数不能为空";
        }
        $list = DB::table('opus')->where('user_id',$user_id)->select('id','url')->limit($limit)->get()->toArray();
        $ids = array_column($list, 'id');
        $imgs = [];
        $ossObj = new Oss();
        foreach ($list as $key => $value) {
            $imgs[] = str_replace(env('APP_FILES_URL').'/', '', $value->url);
        }
        DB::table('opus')->whereIn('id',$ids)->delete();
        $res = $ossObj->batchDeleteObject($imgs);
        print_r($res);
        print_r($ids);

    }

    public function ceshi(){
        set_time_limit(0);

        $list = DB::table('tmp')->get();
        foreach ($list as $key => $value) {
            $info = DB::table('user')->where('email',$value->email)->first();
            if ($info) {
                $isPay = '否';
                $order = DB::table('pay_order')->where('device_id',$info->device_id)->where('status',1)->where('created_at','>=','2023-09-22 01:30:00')->count();
                $open = DB::table('user_open_log')->where('device_id',$info->device_id)->orderBy('id','desc')->limit(1)->first();
                if ($order > 0) {
                    $isPay = '是';
                }
                $time = $open ? $open->created_at : '';
                DB::table('tmp')->where('id',$value->id)->update(['is_pay'=>$isPay,'time'=>$time]);   
            }

        }
        echo 'ok';die;

    }

    public function formatOrderRefundTime(){
        set_time_limit(0);
        $list = DB::table('pay_order')->where('status',2)->get();
        foreach ($list as $key => $value) {
            $extend = empty($value->extend) ? [] : json_decode($value->extend, true);
            $refundData = empty($extend) ? [] : $extend['refundData'] ?? [];
            if ($refundData) {
                $time = substr($refundData['eventTimeMillis'], 0, 10);
                $refund_time = date('Y-m-d H:i:s', $time);
                DB::table('pay_order')->where('id',$value->id)->update(['refund_time'=>$refund_time]);
            }
        }
        echo 'ok';die;

    }

    
    /**
     * 视频中心-回调通知
     */
    public function videoWebHooks(Request $request){

        $data = $request->post();
        if (empty($data)) {
            $data = file_get_contents("php://input");
            $data = json_decode($data, true);
        }

        Log::info('videoWebHooks'.$data['taskId'], [$data]);
        $data['task_id'] = $data['taskId'];
        $res = (new Task())->webVedioHooks($data);
        $data = $request->post();
        return $this->buildReturn(Code::SUCCESS, $data);
        // return json_encode(['code'=>$res['code'], 'msg'=>$res['msg']]);
        
    }


    /**
     * 视频中心-图生视频回调通知
     */
    public function imageVideoWebHooks(Request $request){

        $data = $request->post();
        if (empty($data)) {
            $data = file_get_contents("php://input");
            $data = json_decode($data, true);
        }

        Log::info('videoWebHooks'.$data['taskId'], [$data]);
        $data['task_id'] = $data['taskId'];
        $res = (new Task())->webImageVedioHooks($data);
        $data = $request->post();
        return $this->buildReturn(Code::SUCCESS, $data);
        // return json_encode(['code'=>$res['code'], 'msg'=>$res['msg']]);
        
    }



}
